var Weapon = require("Weapon");
var EnemyDamager = require("EnemyDamager");
var UIController = require("UIController");
var Player = require("PlayerController");

cc.Class({
    extends: Weapon,

    properties: {
        degree : {
			default: 0,
			type: cc.Integer,
			visible: false,
		},
        radians : {
			default: 0,
			type: cc.Float,
			visible: false,
		},


        needle: cc.Prefab,
        visibleRange: cc.Node,


    },

    // LIFE-CYCLE CALLBACKS:


    onLoad () {
        this.degree = 0;
        this.playerDegree = 0;
    },

    start () {
		this.spawnNeedles();
    },

    update (dt) {

		if (Player.instance.getPlayerDrgree() != null) {
			this.playerDegree = Player.instance.getPlayerDrgree();
		};
	
		if (this.statsUpdated == true) {
			this.statsUpdated = false;

			this.unscheduleAllCallbacks();
			this.spawnNeedles();
		}
	
    },

	spawnNeedles(){
		this.schedule(() => {
			this.schedule(() => {

				let needleBullet = cc.instantiate(this.needle);
				//针弹角度处理

				//console.log(this.visibleRange.getComponent('VisibleRange').enemiesInVisibleRange.length);
				if(this.visibleRange.getComponent('VisibleRange').enemiesInVisibleRange.length == 0){

					this.radians = cc.misc.degreesToRadians(this.playerDegree);

					needleBullet.angle = -this.playerDegree;
				}
				else{
					this.degree = this.visibleRange.getComponent('VisibleRange').closestEnemyDegree;
					this.radians = cc.misc.degreesToRadians(this.degree);
					needleBullet.angle = -this.degree;
				}

				needleBullet.parent = cc.find('Canvas');
				
				needleBullet.setPosition(this.node.convertToWorldSpaceAR(cc.v2(this.position)).sub(cc.v2(cc.find('Canvas').position)));

				this.setStats(needleBullet);


				let needleShot = cc.tween(needleBullet)
					//.to(this.stats[this.weaponLevel].range / this.stats[this.weaponLevel].speed, { position: cc.v2(this.stats[this.weaponLevel].range * Math.sin(this.radians), this.stats[this.weaponLevel].range * Math.cos(this.radians)).add(this.node.convertToWorldSpaceAR(cc.v2(this.position))).sub(cc.v2(cc.find('Canvas').position)) })
					.by(this.stats[this.weaponLevel].range / this.stats[this.weaponLevel].speed, { position: cc.v2(this.stats[this.weaponLevel].range * Math.sin(this.radians), this.stats[this.weaponLevel].range * Math.cos(this.radians)) })
					
					.removeSelf()
					.start();

			}, 0.15, this.stats[this.weaponLevel].amount - 1);

			
		}, this.stats[this.weaponLevel].duration);
	},

    setStats (needleBullet) {
		needleBullet.getComponent('EnemyDamager').isBullet = true;
		needleBullet.getComponent('EnemyDamager').validHits = 3;

		needleBullet.getComponent('EnemyDamager').damageAmount = this.stats[this.weaponLevel].damage;
        //this.damager.damageAmount = this.stats[this.weaponLevel].damage;
    },

});
